#include					"MainModule.h"

MainModule::MainModule()
{

}

MainModule::~MainModule()
{

}

void						MainModule::init()
{
	_opMap[CONNECT] = &MainModule::connect;
}

void						MainModule::interpret(Packet * packet)
{
	ProtocolMain *prot = packet->getData<ProtocolMain>(1);
	if (prot != NULL)
	{
		if (_opMap.find(*prot) != _opMap.end())
			(this->*_opMap[*prot])(packet);
		else
			std::cout << "[CRITICAL] Can't find operator [" << (unsigned int) *prot << "] on mainmodule" <<  std::endl;
	}
	else
		std::cout << "[CRITICAL] Error on mainmodule" << std::endl;
}

bool						MainModule::connect(Packet *packet)
{
	unsigned int id = _api->network()->getId(packet->getFrom());
	if (id > 0)
	{
		Packet				answer;
		ProtocolOperator	prot = MAIN;
		ProtocolMain		op = CONNECT;
		State				state;

		answer.init();
		answer.pushData<ProtocolOperator>(&prot);
		answer.pushData<ProtocolMain>(&op);
		std::cout << "[INFO] Connecting client id [" << id << "] ..." << std::endl;
		if (!_api->client()->isConnected(id))
		{
			_api->client()->addConnection(id);
			state = OK;
			answer.pushData<State>(&state);
			_api->network()->send(&answer, id);
			_api->audio()->newBuffer(id);
			std::cout << "=> Done !" << std::endl;
			return true;
		}
		state = KO;
		answer.pushData<State>(&state);
		_api->network()->send(&answer, id);
		_api->network()->closeSocket(id);
		std::cout << "=> Already Connected !" << std::endl;
	}
	return false;
}